<?php
session_start();

// 检查是否已安装
if (file_exists(__DIR__ . '/settings.json') && file_exists(__DIR__ . '/db.php')) {
    die("网站已安装！如需重新安装，请删除 settings.json 和 db.php 文件，然后刷新此页面。");
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $db_host = trim($_POST['db_host']);
    $db_name = trim($_POST['db_name']);
    $db_user = trim($_POST['db_user']);
    $db_pass = trim($_POST['db_pass']);
    $admin_username = trim($_POST['admin_username']);
    $admin_password = trim($_POST['admin_password']);

    // 验证输入
    if (empty($db_host) || empty($db_name) || empty($db_user) || empty($admin_username) || strlen($admin_password) < 6) {
        die("所有字段均为必填，且密码至少6位！");
    }

    // 连接数据库
    $conn = new mysqli($db_host, $db_user, $db_pass);
    if ($conn->connect_error) {
        die("数据库连接失败: " . $conn->connect_error);
    }

    // 创建或清空数据库
    $conn->query("DROP DATABASE IF EXISTS `$db_name`");
    if (!$conn->query("CREATE DATABASE `$db_name` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")) {
        die("创建数据库失败: " . $conn->error);
    }
    $conn->select_db($db_name);

    // 创建表
    $queries = [
        "CREATE TABLE `users` (
            `id` int(11) NOT NULL AUTO_INCREMENT,
            `username` varchar(191) NOT NULL,
            `password` varchar(255) NOT NULL,
            `role` enum('user','admin') DEFAULT 'user',
            PRIMARY KEY (`id`),
            UNIQUE KEY (`username`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
        "CREATE TABLE `categories` (
            `id` int(11) NOT NULL AUTO_INCREMENT,
            `name` varchar(255) NOT NULL,
            PRIMARY KEY (`id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;",
        "CREATE TABLE `files` (
            `id` int(11) NOT NULL AUTO_INCREMENT,
            `name` varchar(255) NOT NULL,
            `path` varchar(255) NOT NULL,
            `upload_time` timestamp DEFAULT CURRENT_TIMESTAMP,
            `user_id` int(11) NOT NULL,
            `category_id` int(11) DEFAULT NULL,
            PRIMARY KEY (`id`),
            FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE,
            FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`) ON DELETE SET NULL
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;"
    ];

    foreach ($queries as $query) {
        if (!$conn->query($query)) {
            die("创建表失败: " . $conn->error);
        }
    }

    // 插入管理员
    $hashed_password = password_hash($admin_password, PASSWORD_DEFAULT);
    $stmt = $conn->prepare("INSERT INTO users (username, password, role) VALUES (?, ?, 'admin')");
    $stmt->bind_param("ss", $admin_username, $hashed_password);
    if (!$stmt->execute()) {
        die("插入管理员失败: " . $stmt->error);
    }

    // 插入默认分类
    $conn->query("INSERT INTO categories (name) VALUES ('默认分类')");

    // 生成 db.php
    $db_content = <<<EOD
<?php
ini_set('session.cookie_httponly', 1);
ini_set('session.use_strict_mode', 1);
session_start();

if (isset(\$_SESSION['last_activity']) && (time() - \$_SESSION['last_activity'] > 1800)) {
    session_unset();
    session_destroy();
    header("Location: login.php");
    exit;
}
\$_SESSION['last_activity'] = time();

if (!isset(\$_SESSION['csrf_token'])) {
    \$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

\$host = '$db_host';
\$dbname = '$db_name';
\$username = '$db_user';
\$password = '$db_pass';

try {
    \$conn = new mysqli(\$host, \$username, \$password, \$dbname);
    if (\$conn->connect_error) {
        die("数据库连接失败: " . \$conn->connect_error);
    }
    header("Content-Security-Policy: default-src 'self'; script-src 'self' /assets/bootstrap/js/bootstrap.bundle.min.js;");
} catch (Exception \$e) {
    die("数据库错误: " . \$e->getMessage());
}
?>
EOD;
    file_put_contents(__DIR__ . '/db.php', $db_content);

    // 生成 settings.json
    $settings = [
        'title' => '私人网盘',
        'max_upload_size' => 10 * 1024 * 1024,
        'allowed_file_types' => ['jpg', 'jpeg', 'png', 'pdf', 'txt', 'doc', 'docx'],
        'registration_enabled' => true,
        'announcement' => '欢迎使用私人网盘！',
        'site_domain' => 'http://localhost',
        'upload_dir' => 'uploads/',
        'max_files_per_user' => 100,
        'theme' => 'light',
        'file_expiry_days' => 0
    ];
    file_put_contents(__DIR__ . '/settings.json', json_encode($settings, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));

    // 创建 uploads 目录
    if (!is_dir(__DIR__ . '/uploads') && !mkdir(__DIR__ . '/uploads', 0755, true)) {
        die("无法创建 uploads 目录！");
    }
    chmod(__DIR__ . '/uploads', 0755);

    echo "<script>alert('安装成功！请删除 install.php 文件。'); window.location.href='index.php';</script>";
    exit;
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>安装 - 私人网盘</title>
    <link href="/assets/bootstrap/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container py-5">
        <h2>私人网盘安装</h2>
        <form method="POST">
            <div class="mb-3">
                <label for="db_host" class="form-label">数据库主机</label>
                <input type="text" class="form-control" id="db_host" name="db_host" value="localhost" required>
            </div>
            <div class="mb-3">
                <label for="db_name" class="form-label">数据库名称</label>
                <input type="text" class="form-control" id="db_name" name="db_name" required>
            </div>
            <div class="mb-3">
                <label for="db_user" class="form-label">数据库用户名</label>
                <input type="text" class="form-control" id="db_user" name="db_user" required>
            </div>
            <div class="mb-3">
                <label for="db_pass" class="form-label">数据库密码</label>
                <input type="password" class="form-control" id="db_pass" name="db_pass">
            </div>
            <div class="mb-3">
                <label for="admin_username" class="form-label">管理员用户名</label>
                <input type="text" class="form-control" id="admin_username" name="admin_username" required>
            </div>
            <div class="mb-3">
                <label for="admin_password" class="form-label">管理员密码（至少6位）</label>
                <input type="password" class="form-control" id="admin_password" name="admin_password" required>
            </div>
            <button type="submit" class="btn btn-primary">安装</button>
        </form>
    </div>
    <script src="/assets/bootstrap/js/bootstrap.bundle.min.js"></script>
</body>
</html>